<template>
  <el-form
    ref="userForm"
    :rules="rules"
    :model="userInfo"
    label-width="120px"
    style="margin-left: 120px; margin-top: 30px"
  >
    <el-form-item label="姓名:" prop="username">
      <el-input v-model="userInfo.username" style="width:300px" />
    </el-form-item>
    <el-form-item label="密码:" prop="password">
      <el-input v-model="userInfo.password" type="password" style="width:300px" />
    </el-form-item>
 
    <el-form-item>
      <el-button type="primary" @click="hSubmit">更新</el-button>
    </el-form-item>
 </el-form>
</template>
<script>
import { getUserDetailById } from '@/api/user'
import { saveUserDetailById } from '@/api/employees'
  export default {
    data() {
        return {
          // userId:this.$route.query.id  , //查询参数的接收方式
           userId:this.$route.params.id  , //路径参数的接收方式
          userInfo: {
              username: '',
              password: '',
             
            },
            rules:{
                username: [{required:true,message:'用户名不能为空',trigger:'blur'}],
                password: [{required:true,message:'密码不能为空',trigger:'blur'}]
            }

        }
      },
      created(){
        this.loadUserDetailById()
      },
      methods:{
        // 兜底校验
        hSubmit(){
          this.$refs.userForm.validate((valid)=>{
             if(!valid) return // 校验失败
             this.updataUserDetailById()
             
          })
        },
      //  更新用户信息
      async updataUserDetailById(){
        try {
          const res = await saveUserDetailById(this.userInfo)
          console.log('saveUserDetailById', res)
          // 更新成功后返回上一个页面
          this.$router.back()
        } catch (err) {
          console.log('saveUserDetailById', err)
        }
      },
      //  获取用户信息 填充到表单中
      async  loadUserDetailById(){
        try {
          const res = await getUserDetailById(this.userId)
          console.log('getUserDetailById', res)
          // 保存数据
          // this.userInfo=res.data  //为了让密码不显示 可以下面的操作
          this.userInfo={...res.data,password:''}  //意思就是展开res.data,且添加一个password为空的对象
        } catch (err) {
          console.log('getUserDetailById', err)
        }
      },
      }
      }
  
</script>